<template>
  <el-dialog class="dialog" title="资料修改" :visible.sync="visible" @close="onClose" width="1000px">
    <el-form :model="form" ref="form" :rules="rules" label-width="170px">
      <el-form-item label="是否有实体店" prop="isStore">
        <el-radio-group v-model="form.isStore">
          <el-radio label="YES">是</el-radio>
          <el-radio label="NO">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所在地址" prop="address" v-if="form.isStore == 'YES'">
        <span @click="onChooseMap">
          <el-input :readonly="true" style="width: 400px" v-model="form.address"></el-input>
        </span>
        <ChooseMap ref="mapChooseRefs" :isDialog="true" @confirm="onMapConfirm" />
      </el-form-item>
      <el-form-item label="门头照" prop="storeImage" v-if="form.isStore == 'YES'">
        <TheUpload
          ref="storeImageRefs"
          :files="form['storeImage']"
          :maxLength="8"
          @upload="
            (e) => (form['storeImage'] = e.files.map((file) => file.url))
          "
        />
      </el-form-item>
      <h2>服务区域信息</h2>
      <p>订单将按照“重点服务区域”、“优先服务区域”、”普通服务区域“的顺序派单</p>
      <el-form-item label="重点服务区域(1个)" prop="emphasis">
        <el-cascader
          clearable
          :props="{ ...props, multiple: true }"
          v-model="form.emphasis"
          style="width: 400px"
          placeholder="选择重点服务区域"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="优先服务区域(2个)" prop="priority">
        <el-cascader
          clearable
          :props="{ ...props, multiple: true }"
          v-model="form.priority"
          style="width: 400px"
          placeholder="选择优先服务区域"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="普通服务区域(最多3个)" prop="common">
        <el-cascader
          clearable
          :props="{ ...props, multiple: true, field: 'common' }"
          v-model="form.common"
          style="width: 400px"
          placeholder="选择普通服务区域"
        ></el-cascader>
      </el-form-item>
      <!-- <el-form-item label="服务品类" prop="cates">
        <el-input
          type="textarea"
          v-model="form.cates"
          style="width: 400px"
        ></el-input>
      </el-form-item>-->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose">返 回</el-button>
      <el-button type="primary" @click="handleSubmit">保 存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import TheUpload from "@/components/TheUpload";
import ChooseMap from "@/components/Map/chooseMap.vue";

import {
  apiCommonDistrict,
  apiWorkerUpdateStoreAndArea
} from "@/api/worker.js";
export default {
  components: { TheUpload, ChooseMap },
  props: {
    workerId: {
      type: String,
      default: ""
    },
    workerInfo: null
  },
  data() {
    const _this = this;
    return {
      visible: false,
      form: {
        isStore: "",
        address: "",
        addressLongitude: "",
        addressLatitude: "",
        storeImage: [],
        emphasis: [],
        priority: [],
        common: []
        // cates: [],
      },
      rules: {
        isStore: [
          {
            required: true,
            message: "请选择是否有实体店",
            trigger: "change"
          }
        ],
        address: [
          {
            required: true,
            message: "请选择所在地址",
            trigger: "change"
          }
        ],
        storeImage: [
          {
            required: true,
            message: "请上传门头照",
            trigger: "change"
          }
        ],
        emphasis: [
          {
            required: true,
            message: "请选择重点服务区域",
            trigger: "change"
          },
          {
            len: 1,
            type: "array",
            message: "请选择1个重点服务区域",
            trigger: "blur"
          }
        ],
        priority: [
          {
            required: true,
            message: "请选择优先服务区域",
            trigger: "change"
          },
          {
            len: 2,
            type: "array",
            message: "请选择2个优先服务区域",
            trigger: "blur"
          }
        ]

        // cates: [
        //   {
        //     type: "array",
        //     required: true,
        //     message: "请选择服务品类",
        //     trigger: "change",
        //   },
        // ],
      },
      props: {
        lazy: true,
        value: "items",
        async lazyLoad(node, resolve) {
          let field = "";
          if (node.level > 0) {
            field = node.config.field;
          }
          const nodes = await _this.getDistrict(
            node.level > 0 ? node.value.id : 0,
            field
          );
          resolve(nodes);
        }
      }
    };
  },
  watch: {
    "form.emphasis": {
      deep: true,
      handler(nVal, oVal) {
        if (nVal.length >= 2) {
          this.$message.warning("最多只支持选择1项");
          this.$nextTick(() => {
            this.form.emphasis = oVal;
          });
        }
      }
    },
    "form.priority": {
      deep: true,
      handler(nVal, oVal) {
        if (nVal.length >= 3) {
          this.$message.warning("最多只支持选择2项");
          this.$nextTick(() => {
            this.form.priority = oVal;
          });
        }
      }
    },
    "form.common": {
      deep: true,
      handler(nVal, oVal) {
        if (nVal.length >= 4) {
          this.$message.warning("最多只支持选择3项");
          this.$nextTick(() => {
            this.form.common = oVal;
          });
        }
      }
    }
  },
  mounted() {},
  methods: {
    onChooseMap() {
      this.$refs.mapChooseRefs.open();
    },
    handleSubmit() {
      console.log(this.form);

      this.$refs["form"].validate(valid => {
        if (valid) {
          const { form } = this;
          const areas = [];
          form.emphasis.forEach(item => {
            let serviceAreaName = "",
              serviceAreaId = "",
              serviceLevel = "IMPORTANT_POINT";
            item.forEach((dd, ii) => {
              serviceAreaName += dd.name;
              if (ii == item.length - 1) {
                serviceAreaId = dd.id;
              }
            });
            areas.push({
              serviceAreaName,
              serviceAreaId,
              serviceLevel
            });
          });
          form.priority.forEach(item => {
            let serviceAreaName = "",
              serviceAreaId = "",
              serviceLevel = "PRECEDENCE";
            item.forEach((dd, ii) => {
              serviceAreaName += dd.name;
              if (ii == item.length - 1) {
                serviceAreaId = dd.id;
              }
            });
            areas.push({
              serviceAreaName,
              serviceAreaId,
              serviceLevel
            });
          });
          form.common.forEach(item => {
            let serviceAreaName = "",
              serviceAreaId = "",
              serviceLevel = "ORDINARY";
            item.forEach((dd, ii) => {
              serviceAreaName += dd.name;
              if (ii == item.length - 1) {
                serviceAreaId = dd.id;
              }
            });
            areas.push({
              serviceAreaName,
              serviceAreaId,
              serviceLevel
            });
          });
          const params = {
            workerId: this.workerId,
            storesFlag: form.isStore,
            storesImageUrl: form.storeImage.join(","),
            address: form.address,
            addressLongitude: form.addressLongitude,
            addressLatitude: form.addressLatitude,
            areas: areas
          };
          apiWorkerUpdateStoreAndArea(params).then(res => {
            this.$message({
              type: "success",
              message: "更新成功"
            });
            this.onClose();
            this.$emit("editStoreSuccess");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    onMapConfirm(info) {
      this.form.address = info.name;
      this.form.addressLatitude = info.lat;
      this.form.addressLongitude = info.lng;
    },
    getDistrict(pid, field) {
      return new Promise((resolve, reject) => {
        apiCommonDistrict({ pid })
          .then(res => {
            resolve(
              res.data.map(item => {
                return {
                  value: item.id,
                  items: item,
                  label: item.name,
                  type: item.level,
                  leaf:
                    field && field === "common"
                      ? item.level == "area"
                      : item.level == "street"
                };
              })
            );
          })
          .catch(err => {
            reject([]);
          });
      });
    },
    onClose() {
      this.$refs.form.resetFields();
      this.visible = false;
    },
    open() {
      this.visible = true;
      this.$nextTick(() => {
        this.form = {
          isStore: this.workerInfo.storeHistory.storesFlag,
          address:this.workerInfo.storeHistory.address,
          // addressLongitude:this.workerInfo.storeHistory.addressLongitude,
          // addressLatitude: this.workerInfo.storeHistory.addressLatitude,
          // storeImage: this.workerInfo.storeHistory.storesImageUrl.split(',').filter(item=>item),
          // emphasis: [],
          // priority: [],
          // common: []
        };
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__body {
  max-height: 75vh;
  overflow-y: auto;
}
</style>
